package cn.lanqiao.bigDate.web.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class LogoutInterceptor implements HandlerInterceptor {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Cookie[] cookies=request.getCookies();
		if(cookies!=null&&cookies.length>0){
			Arrays.stream(cookies).filter(cookie -> cookie.getName().equals("Authorization")).forEach(cookie -> {
				try{
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					String authHeader= URLDecoder.decode((String)cookie.getValue(),request.getCharacterEncoding());
					String token=authHeader.substring(7);
					stringRedisTemplate.opsForSet().add("blackList",token);
					stringRedisTemplate.expire("blackList",15,TimeUnit.MINUTES);
				}catch(UnsupportedEncodingException e){
					e.printStackTrace();
				}
			});
		}
		response.sendRedirect("/bigDateWeb/toLogin");
		return false;
	}

}